import React, { Component } from 'react';
import styles from './index.less';
import { Button, Drawer, Icon, Popconfirm, Table, Upload } from 'antd';
import IconFont from '@/components/IconFont';
import BaseComponent from '@/components/BaseComponent';
import { connect } from 'dva';
import { DivFooter, LFlexHDiv } from '@/components/MHtmlTag';

const { Dragger } = Upload;

/**
 * 上传图片组件
 */
@connect(({ user, detaileddatareporting, loading }) => ({
  currentUser: user.currentUser,
  isRunning: loading.effects['detaileddatareporting/execFileParse'],
}))
class UploadImageView extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 文件列表
      fileList: [],
    };
  }

  columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '状态',
      key: 'isUploading',
      render: (text, record) => {
        const { isUploading } = record;
        if (isUploading) {
          return <span style={{ color: '#E94738' }}>上传中...</span>;
        } else {
          return <span style={{ color: '#32A44E' }}>上传成功</span>;
        }
      },
    },
    {
      title: '操作',
      key: 'operate',
      render: (text, record, index) => {
        return (
          <Popconfirm
            title="确定执行当前操作吗?"
            onConfirm={() => {
              this.handleDelFileItem(record);
            }}
          >
            <Button type="link">移除</Button>
          </Popconfirm>
        );
      },
    },
  ];

  render() {
    const { onClose, record, visible, files } = this.props;

    const props = {
      name: 'file',
      multiple: true,
      action: `/api/file/file/uploadFile4CerDetailReport?user=${this.props.currentUser.id}`,
      accept: '.jpg,.jpeg,.png,.pdf',
      headers: {
        authorization: 'authorization-text',
      },
      showUploadList: false,
      onChange: this.handleOnUploadChange,
      beforeUpload: this.handleBeforeUpload,
    };

    return (
      <Drawer
        title={'上传图像'}
        placement="right"
        width={'55%'}
        maskClosable={false}
        closable={true}
        onClose={e => {
          if (onClose) {
            onClose(e);
          }
        }}
        visible={visible}
      >
        <div className={styles.uploadImageView}>
          <Dragger {...props}>
            <IconFont type={'icon-yunshangchuan'} style={{ fontSize: '48px' }}></IconFont>
            <p className="ant-upload-text">点击或拖拽内镜/病理图像文件到此区域进行上传</p>
            <div>
              内镜图像格式:<span className={styles.importantLabel}>内镜_姓名_日期</span>
              <span>(如:内镜_患者姓名_20221001)</span>
            </div>
            <div>
              内镜图像格式:<span className={styles.importantLabel}>内镜_姓名_内镜号</span>
              <span>(如:内镜_患者姓名_123456)</span>
            </div>
            <div>
              病理图像格式:<span className={styles.importantLabel}>病理_姓名_日期</span>
              <span>(如:病理_患者姓名_20221001)</span>
            </div>
            <div>
              病理图像格式:<span className={styles.importantLabel}>病理_姓名_病理号</span>
              <span>(如:病理_患者姓名_123456)</span>
            </div>
          </Dragger>
          <Table
            dataSource={this.state.fileList}
            columns={this.columns}
            size={'small'}
            style={{ marginTop: '8px' }}
          />
        </div>

        <DivFooter>
          <LFlexHDiv>
            <LFlexHDiv flex={'1'} justifyContent={'center'}>
              <Button
                style={{
                  marginRight: 8,
                  width: '120px',
                }}
                onClick={() => {
                  if (onClose) {
                    onClose();
                  }
                }}
              >
                取消
              </Button>

              <Popconfirm
                title="确认执行当前操作吗?"
                onConfirm={this.handleSubmit}
                okText="是"
                cancelText="否"
              >
                <Button
                  style={{
                    marginRight: 8,
                    width: '120px',
                  }}
                  type="primary"
                >
                  提交
                </Button>
              </Popconfirm>
            </LFlexHDiv>
          </LFlexHDiv>
        </DivFooter>
      </Drawer>
    );
  }

  handleSubmit = () => {
    const { fileList } = this.state;
    if (fileList.length === 0) {
      this.errorMessage('您还没有上传任何文件');
    } else {
      const ids = fileList.map(each => each.fileId).join('|');
      // console.log(ids);
      const hide = this.loadingMessage('操作中...');
      this.execHttp('detaileddatareporting/execFileParse', {
        ids,
        user: this.props.currentUser.id,
      })
        .then(resp => {
          if (hide) {
            hide();
          }
          this.successMessage('文件处理中,处理结果将自动绑定到对应的详情数据当中');
          this.setState({
            fileList: [],
          });
        })
        .catch(reason => {
          if (hide) {
            hide();
          }
        });
    }
  };

  handleDelFileItem = index => {
    const { fileList } = this.state;
    fileList.splice(index, 1);
    this.setState({
      fileList: [...fileList],
    });
  };

  handleOnUploadChange = info => {
    const { status } = info.file;
    if (status !== 'uploading') {
      // 上传中
    }
    if (status === 'done') {
      const response = info.file.response;

      const { fileList } = this.state;
      const obj = fileList.find(each => each.name == info.file.name);
      //上传完成
      if (obj) {
        obj.isUploading = false;
        const { data } = response;
        if (data) {
          obj.fileId = data.fileId;
          obj.key = this.generateId();
        }
      }
      this.setState({
        fileList: [...fileList],
      });

      // console.log(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      this.errorMessage(`${info.file.name} 上传失败`);
      // console.log(`${info.file.name} file upload failed.`);
    }
  };

  /**
   * excel文件上传前的回调
   * @param {*} file
   * @param {*} fileList
   */
  handleBeforeUpload = (file, fileList) => {
    const { type } = file;
    if (type != 'image/jpeg' && type != 'image/png' && type != 'application/pdf') {
      file.status = 'error';
      file.response = '只支持上传jpg/png/pdf格式的文件';
      return false;
    } else {
      const { fileList } = this.state;
      const obj = {
        name: file.name,
        type: file.type,
        isUploading: true,
      };
      fileList.push(obj);
      this.setState({ fileList });
      return true;
    }
  };
}

export default UploadImageView;
